<template>
  <div class="upload-video">
    <div class="upload-video-wrap">
      <video-preview
        v-for="(item, index) in value"
        :key="index"
        :src="item"
        :removable="editable"
        @remove="removeImg(index)"
      />
      <video-preview v-if="addable" class="video-preview--plus" @click="chooseImg">
        <van-icon name="plus" />
      </video-preview>
    </div>
  </div>
</template>

<script>
import VideoPreview from './VideoPreview.vue'
import { Icon } from 'vant'
import Taro from '@tarojs/taro'
import { uploadFile } from '@/api'

export default {
  components: {
    [Icon.name]: Icon,
    VideoPreview
  },
  props: {
    value: {
      type: Array,
      default: () => []
    },
    tag: {
      type: String,
      default: ''
    },
    limit: {
      type: Number,
      default: 1
    },
    editable: {
      type: Boolean,
      default: true
    }
  },
  computed: {
    addable() {
      return this.value.length < this.limit && this.editable
    }
  },
  methods: {
    removeImg(index) {
      this.$emit('input', this.value.filter((item, i) => i !== index))
    },
    previewImg(src) {
      Taro.previewImage({
        urls: this.value,
        current: src
      })
    },
    chooseImg() {
      Taro.chooseMedia({
        count: this.limit - this.value.length,
        sizeType: ['compressed'],
        mediaType: ['video'],
        sourceType: ['album', 'camera'],
        maxDuration: 30,
        success: (res) => {
          const chooseImgs = res.tempFiles.map(res => res.tempFilePath)
          chooseImgs.forEach(url => this.uploadImg(url))
        }
      })
    },
    uploadImg(url) {
      uploadFile(url).then(res => {
        if (res && res.length) {
          this.value.push(res[0] + '?video')
        }
      })
    }
  }
}
</script>

<style lang="less">
.upload-video {
  box-shadow: inset 0px -2px 0px 0px #F5F5F5;
  margin-left: -40px;
  margin-right: -40px;
  padding: 0 40px 8px;

  .text-title {
    display: flex;
    align-items: center;
    font-size: 28px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #666666;
    line-height: 40px;
    margin-bottom: 28px;
  }

  .video-preview-wrap {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    margin-left: -17px;
    margin-right: -17px;
  }

  .video-preview-preview {
    width: 25%;
    text-align: center;
    margin-bottom: 32px;
  }

  .video-preview--plus {
    .video-preview__content {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      box-sizing: border-box;
      border: 2px dashed #cccccc;
      background-color: #fff;

    }
    .van-icon {
      font-size: 80px;
      font-weight: bold;
      color: #cccccc;
    }
  }
}
</style>
